﻿@model ProductIM

@{
    ViewBag.Title = "编辑产品";
    ViewBag.PageTitle = ViewBag.Title + "_内容";
    Layout = "~/Areas/Admin/Views/Shared/_Layout.cshtml";
   
}
@section Header{
<link href="~/bower_components/bootstrap-select/dist/css/bootstrap-select.min.css" rel="stylesheet" />
    <link href="~/plugins/SigFinder/SigFinder.min.css" rel="stylesheet" />
    <link href="~/plugins/webuploader/webuploader.css" rel="stylesheet" />
}



@using (Ajax.BeginForm("EditProduct", null, new AjaxOptions()
{

    HttpMethod = "POST",
    OnBegin = "onBeginSave",
    OnComplete = "onCompleteSave",
    OnSuccess = "updateSuccess"

}, new { @class = "form-horizontal", role = "form" }))
{

    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    @Html.HiddenFor(model => model.Id)
    @*@Html.HiddenFor(model => model.CreatedBy)
    @Html.HiddenFor(model => model.CreatedDate)
    @Html.HiddenFor(model => model.UpdatedBy)
    @Html.HiddenFor(model => model.UpdatedDate)*@


    <div class="panel panel-default sig-panel-tabs">
        <header class="panel-heading">            
          <h3 class="panel-title">@ViewBag.Title</h3>
        </header>

        <section class="panel-body">
            <!-- Nav tabs -->
            <ul class="nav nav-tabs" role="tablist">
                <li role="presentation" class="active"><a href="#product" aria-controls="product" role="tab" data-toggle="tab">@ViewBag.Title</a></li>
                <li role="presentation"><a href="#seo" aria-controls="seo" role="tab" data-toggle="tab">SEO设置</a></li>
            </ul>
            <!-- Tab panes -->
            <div class="tab-content" style="padding-top:30px;">
                <div role="tabpanel" class="tab-pane active" id="product">

                    <div class="form-group">
                        @Html.LabelFor(model => model.ProductNo, new { @class = "col-md-2 control-label" })
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.ProductNo, new { @class = "form-control", placeholder = Labels.ProductNo })
                            @Html.ValidationMessageFor(model => model.ProductNo)
                        </div>

                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.ProductName, new { @class = "col-md-2 control-label" })
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.ProductName, new { @class = "form-control", placeholder = Labels.ProductName })
                            @Html.ValidationMessageFor(model => model.ProductName)
                        </div>

                    </div>


                    <div class="form-group">
                        @Html.LabelFor(model => model.PostCategoryIds, new { @class = "col-md-2 control-label" })
                        <div class="col-md-10">
                            @Html.ListBoxFor(model => model.PostCategoryIds, (SelectList)ViewBag.Categories, new { @class = "form-control selectpicker" })
                            @Html.ValidationMessageFor(model => model.PostCategoryIds)</div>
                    </div>



                    <div class="form-group">
                        @Html.LabelFor(model => model.Thumbnail, new { @class = "col-md-2 control-label" })
                        <div class="col-md-10">
                            <div class="input-group">
                                @Html.TextBoxFor(model => model.Thumbnail, new { @class = "form-control", placeholder = Labels.Thumbnail })
                                <span class="input-group-btn">
                                    <button class="btn btn-default" id="btnThumbnail" type="button">浏览…</button>
                                </span>
                            </div><!-- /input-group -->
                            <span class="help-block">@string.Format("图像大小：{0}x{1} 像素", SettingsManager.Product.ThumbWidth, SettingsManager.Product.ThumbHeight)</span>                  
                            @Html.ValidationMessageFor(model => model.Thumbnail)
                        </div>
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.ImageUrl, new { @class = "col-md-2 control-label" })
                        <div class="col-md-10">
                            <div id="imagePicker">选择图片</div>
                            @Html.HiddenFor(m => m.ImageUrl)
                            <span class="help-block">
                                图像大小：1240x790 像素
                            </span>
                            @Html.ValidationMessageFor(model => model.ImageUrl)
                        </div>
                    </div>

                    <div class="form-group">
                        <div id="uploader-demo" class="col-md-10 col-md-offset-2">
                            <!--用来存放item-->
                            <div id="imageList" class="uploader-list">
                                @{
                                    if (!string.IsNullOrEmpty(Model.ImageUrl))
                                    {
                                        var images = Model.ImageUrl.Split('|');
                                        foreach (var item in images)
                                        {
                                            <div class="file-item thumbnail pull-left  m-r-10 m-b-10 upload-state-done">
                                                <img src="@string.Format("{0}?width=120&height=90&mode=crop", item)">
                                                <div class="info">
                                                    <button type="button" data-img="@item" class="btn btn-danger btn-sm btnRemove">删除</button>
                                                </div>
                                            </div>
                                        }
                                    }
                                }
                            </div>

                        </div>
                    </div>


                    <div class="form-group">
                        @Html.LabelFor(model => model.Body, new { @class = "col-md-2 control-label" })
                        <div class="col-md-10">
                            @Html.TextAreaFor(model => model.Body, new { @class = "form-control", placeholder = Labels.Content })
                            @Html.ValidationMessageFor(model => model.Body)
                        </div>

                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.Description, new { @class = "col-md-2 control-label" })
                        <div class="col-md-10">
                            @Html.TextAreaFor(model => model.Description, new { @class = "form-control", placeholder = Labels.Description })                        
                            @Html.ValidationMessageFor(model => model.Description)
                        </div>
                    </div>


                  


                    <div class="form-group">
                        <div class="col-md-10 col-md-offset-2">
                            <div class="checkbox">
                                <label>
                                    @Html.CheckBoxFor(model => model.Recommend)  @Html.DisplayNameFor(model => model.Recommend)  @Html.ValidationMessageFor(model => model.Recommend)
                                </label>
                            </div>
                        </div>
                    </div>


                    <div class="form-group">
                        <div class="col-md-10 col-md-offset-2">
                            <div class="checkbox">
                                <label>
                                    @Html.CheckBoxFor(model => model.Active)  @Html.DisplayNameFor(model => model.Active)  @Html.ValidationMessageFor(model => model.Active)
                                </label>
                            </div>
                        </div>
                    </div>

                </div>
                <div role="tabpanel" class="tab-pane" id="seo">
                    <div class="form-group">
                        @Html.LabelFor(model => model.Title, new { @class = "col-md-2 control-label" })
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.Title, new { @class = "form-control", placeholder = Labels.Title })
                       
                            @Html.ValidationMessageFor(model => model.Title)
                        </div>
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.Keywords, new { @class = "col-md-2 control-label" })
                        <div class="col-md-10">
                            @Html.TextBoxFor(model => model.Keywords, new { @class = "form-control", placeholder = Labels.KeyWords })
                      
                            @Html.ValidationMessageFor(model => model.Keywords)
                        </div>
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.SEODescription, new { @class = "col-md-2 control-label" })
                        <div class="col-md-10">
                            @Html.TextAreaFor(model => model.SEODescription, new { @class = "form-control", placeholder = Labels.Description })
                       
                            @Html.ValidationMessageFor(model => model.SEODescription)
                        </div>
                    </div>

                </div>
            </div><!-- /.tab-content -->
        </section>
        <footer class="panel-footer text-center">
            <button type="submit" class="btn btn-primary" id="btnSave"><i class="fa fa-save fa-fw"></i>  @Buttons.Update </button>
            <a href="@Url.Action("Index")" class="btn btn-default"><span class="glyphicon glyphicon-arrow-left"></span> @Buttons.Back</a>
        </footer>

    </div>

}

@Html.Action("PopuFinder", "File")

@section Footer {
    @Scripts.Render("~/bundles/jqueryvalWithBootstrap")
    <script src="/Plugins/webuploader/webuploader.min.js"></script>
    <script src="/Plugins/SigFinder/FileManager.js"></script>
    <script src="~/plugins/tinymce/tinymce.min.js"></script>
    <script src="~/plugins/tinymce/langs/zh_CN.js"></script>
    <script src="~/bower_components/bootstrap-select/dist/js/bootstrap-select.min.js"></script>
    <script src="~/bower_components/bootstrap-select/dist/js/i18n/defaults-zh_CN.min.js"></script>


    <script>


         var $list = $("#imageList");
        // 初始化Web Uploader
        var uploader = WebUploader.create({
            // 选完文件后，是否自动上传。
            auto: true,
            // swf文件路径
            swf:  '/plugins/webuploader/js/Uploader.swf',
            // 文件接收服务端。
            server: "@Url.Action("UpLoadImages")",

            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#imagePicker',

            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            }
        });


        // 当有文件添加进来的时候
        uploader.on('fileQueued', function (file,result) {
            var $li = $(
                    '<div id="' + file.id + '" class="file-item thumbnail pull-left  m-r-10 m-b-10">' +
                        '<img>' +
                        '<div class="info"><button type="button" data-img="" class="btn btn-danger btn-sm btnRemove">删除</button></div>' +
                    '</div>'
                    ),
                $img = $li.find('img');


            // $list为容器jQuery实例
            $list.append($li);


        });

        // 文件上传过程中创建进度条实时显示。
        uploader.on('uploadProgress', function (file, percentage) {
            var $li = $('#' + file.id),
                $percent = $li.find('.progress span');

            // 避免重复创建
            if (!$percent.length) {
                $percent = $('<p class="progress"><span></span></p>')
                        .appendTo($li)
                        .find('span');
            }

            $percent.css('width', percentage * 100 + '%');
        });

        // 文件上传成功，给item添加成功class, 用样式标记上传成功。
        uploader.on('uploadSuccess', function (file,result) {
            $('#' + file.id).addClass('upload-state-done');
            $('#' + file.id + ' img').attr("src", result.fileName + "?width=120&height=90&mode=crop");
            $('#' + file.id + ' button').attr("data-img", result.fileName);

            var img = $("#ImageUrl").val();
            if (img.length === 0) {
                $("#ImageUrl").val(result.fileName);
            } else {
                img = img + "|" + result.fileName;
                $("#ImageUrl").val(img);
            }
            //console.log(result);
        });

        // 文件上传失败，显示上传出错。
        uploader.on('uploadError', function (file) {
            var $li = $('#' + file.id),
                $error = $li.find('div.error');

            // 避免重复创建
            if (!$error.length) {
                $error = $('<div class="error"></div>').appendTo($li);
            }

            $error.text('上传失败');
        });

        // 完成上传完了，成功或者失败，先删除进度条。
        uploader.on('uploadComplete', function (file) {
            $('#' + file.id).find('.progress').remove();
            uploader.reset();
        });


       function SetThumbnail() {
            var fileUrl = $("#fileList .item.active").attr("data-file");
            $('#Thumbnail').val(fileUrl);
            $('#fileManagerModal').modal('hide');
        }

        function onBeginSave() {
            $("#btnSave i").removeClass("fa-save").addClass("fa-spinner fa-spin");
        }
        function onCompleteSave() {
            $("#btnSave i").removeClass("fa-spinner fa-spin").addClass("fa-save");
        }

        function updateSuccess(data) {
            var title = '@ViewBag.Title';
        Common.ShowBox(data.Status, data.Message, title);
    }

    tinymce.init({
            selector: '#Body',  // change this value according to your HTML
            height: 400,
            language: 'zh_CN',
            theme: 'modern',
            convert_urls: false,
            plugins: [
              'advlist autolink lists link image charmap print preview hr anchor pagebreak',
              'searchreplace wordcount visualblocks visualchars code fullscreen',
              'insertdatetime media nonbreaking save table contextmenu directionality',
              'emoticons template paste textcolor colorpicker textpattern imagetools codesample toc'
            ],
            toolbar1: 'undo redo | insert | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image print preview media | forecolor backcolor emoticons | codesample',
            image_advtab: true,
            templates: [
              { title: 'Test template 1', content: 'Test 1' },
              { title: 'Test template 2', content: 'Test 2' }
            ],
            //picture manager
            file_browser_callback: callSigFinder,
            templates: [
        { title: 'Some title 1', description: 'Some desc 1', content: 'My content' },
        { title: 'Some title 2', description: 'Some desc 2', url: 'development.html' }
            ]

        });
        function callSigFinder(field_name, url, type, win) {
            var roxyFileman = '@Url.Action("FinderForTinyMCE","File",new { area="Admin"})';
            tinyMCE.activeEditor.windowManager.open({
                file: roxyFileman,
                title: 'SigFinder',
                width: 850,
                height: 655,
                resizable: "yes",
                plugins: "media",
                inline: "yes",
                close_previous: "no"
            }, { window: win, input: field_name });
            return false;

        }




    $(function () {
        $("#btnThumbnail").on("click", function () {
            $('#fileManagerModal').modal();
            $("#selectImage").unbind('click');
            $("#selectImage").bind("click", function () {
                SetThumbnail();
            });
        });



             $(document).on("click", '.btnRemove', function (e) {
                e.preventDefault();
                var item = $(this).closest(".file-item");
                var imgName = $(this).attr('data-img');
                var url = "@Url.Action("RemoveImage")";

                $.post(url, { img: imgName }, function (data) {

                    if (data.Status === 1) {
                        item.remove();


                        var images = $("#ImageUrl").val();
                        var ar = images.split("|");
                        var i = ar.indexOf(imgName);
                        if (i != -1) {
                            ar.splice(i, 1);
                        }
                        $("#ImageUrl").val(ar.join("|"));

                    }
                    if (data.Status === 2) {
                        toastr.error(data.Message)
                    }
                });

            });


        $('.selectpicker').selectpicker();

             //var $form = $('form');
             //var $validate = $form.validate();
             //var errorClass = "has-error";
             ////var successClass = "has-success";
             //$validate.settings.errorClass = errorClass;
             //var previousEPMethod = $validate.settings.errorPlacement;
             //$validate.settings.errorPlacement = $.proxy(function (error, inputElement) {
             //        if (previousEPMethod) {
             //                previousEPMethod(error, inputElement);
             //            }
             //        inputElement.parent().addClass(errorClass)
             //    }, $form[0]);

             //var previousSuccessMethod = $validate.settings.success;
             //$validate.settings.success = $.proxy(function (error) {
             //        //we first need to remove the class, cause the unobtrusive success method removes the node altogether
             //    error.parent().parent().removeClass(errorClass)
             //        if (previousSuccessMethod) {
             //                previousSuccessMethod(error);
             //            }
             //    });


        });
    </script>
}
